import { resolve, join, extname } from 'path';
import fs from 'fs';

// 加载插件模块
const loadPluginModules = async (folderName) => {
	return new Promise((success) => {
		const modulesPath = resolve(__dirname, folderName);
		const fileNames = fs.readdirSync(modulesPath);
		let modulesImprot = [];
		fileNames.forEach(async (item) => {
			const filePath = join(modulesPath, item);
			if (
				fs.statSync(filePath).isFile() &&
				['.js', '.ts'].includes(extname(filePath))
			) {
				modulesImprot.push(import(`./${folderName}/${item}`));
			}
		});
		const modules = modulesImprot.length ? Promise.all(modulesImprot) : [];
		success(modules);
	});
};

// 处理加载的插件模块
const hanldePluginModules = (pluginsArr = [], rsEnv) => {
	let resModule = []
	pluginsArr.forEach((item) => {
		const funcs = Object.values(item);
		funcs.forEach((it) => {
			resModule.push(it(rsEnv));
		});
	});
	return resModule
};

// 基本配置
const baseCfg = (rsEnv = {}) => {
	return {
		source: {
			alias: {
				'@': resolve(resolve(), './src'),
				"~@": resolve("./src"),
			},
		},
		server: {
			port: 3001
		},
	};
};


// 插件配置
const pluginCfg = async (rsEnv = {}) => {
	
	const [plugins, rsPlugin] = await Promise.all([loadPluginModules('plugins'), loadPluginModules('rspackPlugin')]);
	const rsbuildPlugins = hanldePluginModules(plugins, rsEnv);
	const rspackPlugin = hanldePluginModules(rsPlugin, rsEnv);
	return {
		plugins: rsbuildPlugins,
		rspackPlugin
	};
};

export { baseCfg, pluginCfg };
